package com.zl.learning.json.gson;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GsonTest2 {
    private Gson gson = new Gson();

    @Test
    public void test1() {
        User u = new User();
        List<Integer> numberIds = Arrays.asList(1, 2, 3, 4, 5);
        u.setNumberIds(numberIds);
        List<Integer> _numberIds = gson.fromJson(u.getNumberIds().toString(), new TypeToken<ArrayList<Integer>>() {
        }.getType());
        System.out.println(_numberIds);
        System.out.println(gson.toJson(u));
    }

    @Test
    public void test2() {
        User u = gson.fromJson("{\"id\":0,\"numberIds\":[1,2,3,4,5]}", User.class);
        System.out.println(u.getNumberIds());
        List<Integer> _numberIds = gson.fromJson(u.getNumberIds().toString(), new TypeToken<ArrayList<Integer>>() {
        }.getType());
        System.out.println(_numberIds);
    }

    @Test
    public void test3() {
        User u = new User();
        List<Integer> numberIds = Arrays.asList(1, 2, 3, 4, 5);
        u.setNumberIds(numberIds);
        User u2 = new User();
        u2.setNumberIds(u);
        System.out.println(gson.toJson(u2));
    }

    @Test
    public void test4() {
        User u = gson.fromJson("{\"id\":0,\"numberIds\":{\"id\":0,\"numberIds\":[1,2,3,4,5]}}",User.class);
        User u2 = gson.fromJson(u.getNumberIds().toString(),User.class);
        System.out.println(u2.getNumberIds());
    }

    class User {
        int id;
        String name;
        Object numberIds;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Object getNumberIds() {
            return numberIds;
        }

        public void setNumberIds(Object numberIds) {
            this.numberIds = numberIds;
        }
    }
}
